import is from '../electron/helper/is';
import IPC from '../electron/ipc/dict';

/*别名*/
const IPC_UPDATER = IPC.IPC_UPDATER;

/**
 * 请求主进程检测更新
 * @param delay
 * @return {NodeJS.Timeout}
 */
const renderRequest = delay => setTimeout(() => ipcRenderer.send(IPC_UPDATER.RENDER_REQUEST), delay || 1000);

/**
 * 通知主进程确认更新
 * @param data
 */
const renderConfirm = data => ipcRenderer.send(IPC_UPDATER.RENDER_CONFIRM, data);

/**
 * 初始化
 * @param delay
 * @param CHECK_INFO
 * @param CHECK_ERROR
 * @param PARSE_INFO
 * @param PARSE_ERROR
 * @param NEW_VERSION
 * @param DOWNLOAD_PROGRESS
 * @param DOWNLOAD_INFO
 * @param DOWNLOAD_ERROR
 * @param RUN_SETUP_ERROR
 * @param RUN_SETUP_SUCCESS
 */
function initialize ({
    delay,
    CHECK_INFO,
    CHECK_ERROR,
    PARSE_INFO,
    PARSE_ERROR,
    NEW_VERSION,
    DOWNLOAD_PROGRESS,
    DOWNLOAD_INFO,
    DOWNLOAD_ERROR,
    RUN_SETUP_ERROR,
    RUN_SETUP_SUCCESS
}) {
    /*请求主进程检测更新*/
    renderRequest(delay);

    /*检查更新提示*/
    ipcRenderer.on(IPC_UPDATER.CHECK_INFO, (e, msg) => is.func(CHECK_INFO) && CHECK_INFO(msg));

    /*检查更新错误*/
    ipcRenderer.on(IPC_UPDATER.CHECK_ERROR, (e, msg) => is.func(CHECK_ERROR) && CHECK_ERROR(msg));

    /*解析提示*/
    ipcRenderer.on(IPC_UPDATER.PARSE_INFO, (e, msg) => is.func(PARSE_INFO) && PARSE_INFO(msg));

    /*解析错误*/
    ipcRenderer.on(IPC_UPDATER.PARSE_ERROR, (e, msg) => is.func(PARSE_ERROR) && PARSE_ERROR(msg));

    /*发现新版本*/
    ipcRenderer.on(IPC_UPDATER.NEW_VERSION, (e, data) => is.func(NEW_VERSION) && NEW_VERSION(data));

    /*下载进度*/
    ipcRenderer.on(IPC_UPDATER.DOWNLOAD_PROGRESS, (e, { total, downloaded }) => is.func(DOWNLOAD_PROGRESS) && DOWNLOAD_PROGRESS({ total, downloaded }));

    /*下载提示*/
    ipcRenderer.on(IPC_UPDATER.DOWNLOAD_INFO, (e, msg) => is.func(DOWNLOAD_INFO) && DOWNLOAD_INFO(msg));

    /*下载失败*/
    ipcRenderer.on(IPC_UPDATER.DOWNLOAD_ERROR, (e, msg) => is.func(DOWNLOAD_ERROR) && DOWNLOAD_ERROR(msg));

    /*启动安装包失败*/
    ipcRenderer.on(IPC_UPDATER.RUN_SETUP_ERROR, (e, msg) => is.func(RUN_SETUP_ERROR) && RUN_SETUP_ERROR(msg));

    /*启动安装包成功*/
    ipcRenderer.on(IPC_UPDATER.RUN_SETUP_SUCCESS, (e, msg) => is.func(RUN_SETUP_SUCCESS) && RUN_SETUP_SUCCESS(msg));
}

export default {
    initialize,
    renderRequest,
    renderConfirm
};
